package root.electronclass.electronclass.grade.homework

import android.content.res.ColorStateList
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.appcompat.widget.ListPopupWindow
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.os.bundleOf
import androidx.core.view.forEachIndexed
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.viewModels
import root.electronclass.electronclass.R
import root.electronclass.electronclass.common.base.BasicAdapter
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.databinding.FragmentClassHomeworkStatisticalBinding
import root.electronclass.electronclass.databinding.FragmentClassHomeworkStatisticalItemBinding
import root.electronclass.electronclass.databinding.FragmentClassHomeworkStatisticalSubjectItemBinding
import root.electronclass.electronclass.ext._yyyyMMddHHmm
import root.electronclass.electronclass.ext.doOnTabSelected
import root.electronclass.electronclass.ext.dp
import root.electronclass.electronclass.ext.startFragment
import root.electronclass.electronclass.ext.toEEEE
import root.electronclass.electronclass.grade.homework.viewmodel.ClassHomeworkStatisticalViewModel
import root.electronclass.electronclass.grade.model.ClassHomeworkItem
import root.electronclass.electronclass.grade.viewmodel.WeekType
import root.electronclass.electronclass.grade.widget.SubjectBarItem

/**
 * 电子班牌-班级版-班级空间-班级作业-作业详情
 * @author Lokiy
 * @date 2023/2/18 19:11
 */
class ClassHomeworkStatisticalFragment : ViewBindingFragment<FragmentClassHomeworkStatisticalBinding>() {

    private val viewModel by viewModels<ClassHomeworkStatisticalViewModel>()

    private val itemsAdapter = BasicAdapter<ClassHomeworkItem, FragmentClassHomeworkStatisticalItemBinding> { holder, item ->
        holder.binding.root.backgroundTintList = ColorStateList.valueOf(if (holder.adapterPosition % 2 == 0) 0 else 0xfF7f8f9)
        holder.binding.itemSubject.text = item.subject
        holder.binding.itemStatus.text = item.statusText
        holder.binding.itemDate.text = item.startTime?.toEEEE(_yyyyMMddHHmm)?.replace("星期", "周")
        holder.binding.itemElapsed.text = if (item.elapsedTime > 0) getString(R.string.minute, item.elapsedTime.toInt()) else "-"
        holder.binding.itemAvg.text = if (item.avgTime > 0) getString(R.string.minute, item.avgTime.toInt()) else "-"
        holder.binding.itemPublisher.text = item.creator ?: "-"
        holder.binding.itemCreateTime.text = if (item.createTime.isNullOrEmpty()) "-" else item.createTime
        if (item.status >= 2) {
            holder.binding.itemDetail.text = "查看"
            holder.binding.itemDetail.setTextColor(resources.getColor(R.color.c_brand))
            holder.binding.itemDetail.setBackgroundResource(R.drawable.bg_306eff_round_border)
            holder.binding.itemDetail.setOnClickListener {
                startFragment(ClassHomeworkDetailFragment::class.java, bundleOf("id" to item.id, EXTRA_DATA to item))
            }
        } else {
            holder.binding.itemDetail.text = "-"
            holder.binding.itemDetail.setTextColor(0xFF071129.toInt())
            holder.binding.itemDetail.setBackgroundResource(R.color.transparent)
            holder.binding.itemDetail.setOnClickListener(null)
        }
    }

    private val subjectAdapter = BasicAdapter<Pair<String, Int>, FragmentClassHomeworkStatisticalSubjectItemBinding> { holder, item ->
        holder.binding.itemSubject.text = item.first
        holder.binding.itemCount.text = item.second.toString()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.tabLayout.apply {
            resources.getStringArray(R.array.class_homework_statistical_tabs).forEach {
                addTab(newTab().setText(it))
            }
            doOnTabSelected {
                viewModel.selectDayOfWeek.value = it?.position ?: 0
            }
        }
        val padding = 24.dp.toInt()
        binding.studentRecyclerTitle.root.apply {
            val names = resources.getStringArray(R.array.class_homework_statistical_titles)
            forEachIndexed { index, it ->
                val view1: View
                if (it is TextView) {
                    view1 = it
                } else {
                    it as ViewGroup
                    view1 = it.getChildAt(0)
                    view1 as TextView
                }
                view1.setTextColor(0xFFFFFFFF.toInt())
                view1.text = names[index]
            }
            updateLayoutParams<ConstraintLayout.LayoutParams> {
                topMargin = padding
            }
        }
        binding.studentRecycler.adapter = itemsAdapter
        binding.week.text = getString(R.string.class_current_week)
        binding.week.setOnClickListener {
            ListPopupWindow(requireContext()).apply {
                anchorView = it
                isModal = true
                val arrays = arrayOf(getString(R.string.class_last_week), getString(R.string.class_current_week), getString(R.string.class_next_week))
                setAdapter(ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, arrays))
                setOnItemClickListener { _, _, position, _ ->
                    binding.week.text = arrays[position]
                    dismiss()
                    viewModel.selectWeekType.value = if (position == 0) WeekType.LAST else if (position == 1) WeekType.CURRENT else WeekType.NEXT
                }
            }.show()
        }
        binding.status.text = getString(R.string.class_homework_status)
        binding.status.setOnClickListener {
            ListPopupWindow(requireContext()).apply {
                anchorView = it
                isModal = true
                setAdapter(
                    ArrayAdapter(
                        requireContext(),
                        android.R.layout.simple_list_item_1,
                        (0..5).map { ClassHomeworkItem.convertStatusToText(it) })
                )
                setOnItemClickListener { _, _, position, _ ->
                    if (position == 0) {
                        binding.status.text = getString(R.string.class_homework_status)
                    } else {
                        binding.status.text = ClassHomeworkItem.convertStatusToText(position)
                    }
                    dismiss()
                    viewModel.selectStatus.value = position
                }
            }.show()
        }

//        binding.subjectRecycler.adapter = subjectAdapter

        viewModel.data.observe(viewLifecycleOwner) {
            itemsAdapter.notifyChanged(it)
        }
        viewModel.subjectStatistical.observe(viewLifecycleOwner) { list ->
            binding.subjectRecycler.setData(list.map { SubjectBarItem(it.first, it.second) })
        }
    }
}